package DFA;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.RecursiveTask;

public class dfaSumTask extends RecursiveTask<returnPOJO> {
    private int start;
    private int end;
    private static final int segmentation = 1;
    private static final int jishu = 2;
    private HashMap<Integer,ArrayList<Integer>> hash;
    private  TxtReadIn readIn;
    private HashMap<Integer, int[][]> dfaMap;
    public  HashMap<Integer, ArrayList<Integer>> getFinalArray(){
        return readIn.getFinalArray();
    }
    public dfaSumTask(int start, int end, HashMap<Integer, int[][]> dfaMap, TxtReadIn readIn) {

        this.start = start;
        this.end = end;
        this.dfaMap = dfaMap;
        this.readIn =readIn;
        this.hash= getFinalArray();

    }

    @Override
    protected returnPOJO compute() {
        if (end-start == jishu) {
            int mid = (start + end) / 2;
            //分裂子任务
            dfaSumTask subtask1 = new dfaSumTask(start,mid,dfaMap, readIn);
            int[][] dfa1 = dfaMap.get(start);
            int[][] dfa2 = dfaMap.get(mid);
            int[][] dfa3 = dfaMap.get(mid+1);
            ArrayList<Integer> dfa1Final = hash.get(start);
            ArrayList<Integer> dfa2Final = hash.get(mid);
            ArrayList<Integer> dfa3Final = hash.get(mid+1);
            zongHe zongHe1 = new zongHe(dfa1,dfa2,readIn,start,dfa1Final,dfa2Final);
            returnPOJO returnPOJO = zongHe1.finalZonghe();
            int[][] result = returnPOJO.getTemp();
            zongHe zongHe2 = new zongHe(result,dfa3,readIn,mid,returnPOJO.getList(),dfa3Final);//暂时改
            returnPOJO = zongHe2.finalZonghe();
            //调用三个综合的方法
            return returnPOJO;
        }
        if (end - start <= segmentation) {
            int[][] ints0 = dfaMap.get(start);
            int[][] ints1 = dfaMap.get(end);
            ArrayList<Integer> dfa1Final = hash.get(start);
            ArrayList<Integer> dfa2Final = hash.get(end);
            zongHe zongHe = new zongHe(ints0, ints1,readIn,start,dfa1Final,dfa2Final);
            returnPOJO returnPOJO = zongHe.finalZonghe();
            //returnPOJO.setFinalState();
            return returnPOJO;
        }
        else {
            //任务过大 一份为2
            int mid = (start + end) / 2;
            //分裂子任务
            dfaSumTask subtask1 = new dfaSumTask(start,mid,dfaMap, readIn);
            dfaSumTask subtask2 = new dfaSumTask(mid+1,end,dfaMap, readIn);
            //并行运行两个子任务
            invokeAll(subtask1, subtask2);
            //获得子任务的结果
            returnPOJO taskA = subtask1.join();
            returnPOJO taskB = subtask2.join();
            zongHe zongHe = new zongHe(taskA.getTemp(), taskB.getTemp(),readIn,start,taskA.getList(),taskB.getList());
            returnPOJO returnPOJO = zongHe.finalZonghe();
            return returnPOJO;
        }
    }
}
